package com.drawu.drawuspring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drawu.drawuspring.constants.BehaviorConstants;
import com.drawu.drawuspring.domain.DTO.FocusBehaviorDto;
import com.drawu.drawuspring.domain.Result;
import com.drawu.drawuspring.domain.VO.UserVO;
import com.drawu.drawuspring.domain.po.FocusRecord;
import com.drawu.drawuspring.domain.po.Users;
import com.drawu.drawuspring.mapper.FocusRecordMapper;
import com.drawu.drawuspring.service.IFocusRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drawu.drawuspring.service.IUsersService;
import com.drawu.drawuspring.utils.AppThreadLocalUtil;
import com.drawu.drawuspring.utils.BeanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 关注记录表 服务实现类
 * </p>
 *
 * @author hui
 * @since 2024-10-12
 */
@Service
@RequiredArgsConstructor
public class FocusRecordServiceImpl extends ServiceImpl<FocusRecordMapper, FocusRecord> implements IFocusRecordService {

    private final IUsersService usersService;
    private final RedisTemplate redisTemplate;

    /**
     * gz 保存关注记录
     *
     */
    @Override
    public void saveFocusRecord(FocusBehaviorDto dto) {
        FocusRecord focusRecord = new FocusRecord();
        Users user = AppThreadLocalUtil.getUser();
        focusRecord.setUserId(user.getId());
        focusRecord.setFocusId(dto.getFocusId());
        this.save(focusRecord);
    }

    /**
     * gz 删除关注记录
     *
     */
    @Override
    public void deleteFocusRecord(FocusBehaviorDto dto) {
        Users user = AppThreadLocalUtil.getUser();
        QueryWrapper<FocusRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId());
        wrapper.eq("focus_id", dto.getFocusId());
        this.remove(wrapper);
    }

    /**
     * 获取被关注的记录列表
     *
     */
    @Override
    public Result<List<UserVO>> getLikedRecordList() {
        // 1.获取用户id
        Integer userId = AppThreadLocalUtil.getUser().getId();
        // 2.获取Key
        String key = BehaviorConstants.FOCUS_BEHAVIOR + userId.toString() ;
        // 3.从redis中获取数据
        Set ids = redisTemplate.opsForSet().members(key);
        // 4.查询数据库
        List<Users> list = usersService.listByIds(ids);
        // 5.封装返回结果
        List<UserVO> userVOList = BeanUtils.copyList(list, UserVO.class);
        return Result.success(userVOList);
    }
}
